import Taro, {Component, FC, useState, useEffect, useMemo} from '@tarojs/taro'
import {View, Image} from '@tarojs/components'
import './index.scss'

const ScaleImg = ({src, style}) => {
  let [offsetX, setOffsetX] = useState(0)
  let [offsetY, setOffsetY] = useState(0)
  const [zoom, setZoom] = useState(false)
  const [distance, setDistance] = useState(0)
  const [scale, setScale] = useState(1)
  let [offsetLeftX, setOffsetLeftX] = useState(0)
  let [offsetLeftY, setOffsetLeftY] = useState(0)
  let startX = 0
  let startY = 0

  const touchStart = e => {
    if (e.touches.length == 1) {
      const {clientX, clientY} = e.touches[0]
      startX = clientX
      startY = clientY
    } else {
      const xMove = e.touches[1].clientX - e.touches[0].clientX
      const yMove = e.touches[1].clientY - e.touches[0].clientY
      const distanceData = Math.sqrt(xMove * xMove + yMove * yMove)
      setDistance(distanceData)
      setZoom(true)
    }
  }

  // 触摸移动事件
  const touchMove = e => {
    if (e.touches.length == 1) {
      //单指移动,缩放状态，不处理单指
      if (zoom) {
        return
      }
      const {clientX, clientY} = e.touches[0]
      const newoffsetX = clientX - startX
      const newoffsetY = clientY - startY
      startX = clientX
      startY = clientY
      //   let {offsetX, offsetY, offsetLeftX, offsetLeftY} = this.state;
      offsetX += newoffsetX
      offsetY += newoffsetY
      offsetLeftX = -offsetX
      offsetLeftY = -offsetY
      setOffsetX(offsetX)
      setOffsetY(offsetY)
      setOffsetLeftX(offsetLeftX)
      setOffsetLeftY(offsetLeftY)
    } else {
      //双指缩放
      const xMove = e.touches[1].clientX - e.touches[0].clientX
      const yMove = e.touches[1].clientY - e.touches[0].clientY
      const distances = Math.sqrt(xMove * xMove + yMove * yMove)
      const distanceDiff = distances - distance
      const newScale = scale + 0.005 * distanceDiff
      // 缩放比例设置
      if (newScale <= 2.5 && newScale >= 1) {
        setDistance(distance)
        setScale(newScale)
        // this.setState({
        //   distance,
        //   scale: newScale,
        // })
      }
    }
  }

  // 触摸结束事件,重置缩放状态
  const touchEnd = e => {
    if (e.touches.length == 0) {
      //   this.setState({
      //     zoom: false
      //   })
      setZoom(false)
    }
  }
  return (
    <View className="full-img">
      <Image
        // + '&x-oss-process=image/resize,m_fill,h_0,w_1000/format,webp'
        src={src || 'https://sl-mo.yryz.com/static/imgs/userDefault.png'}
        webp
        lazyLoad
        mode="widthFix"
        onTouchStart={e => {
          touchStart(e)
        }}
        onTouchMove={e => {
          touchMove(e)
        }}
        onTouchEnd={e => {
          touchEnd(e)
        }}
        style={{width: 100 * scale + '%'}}
      />
    </View>
  )
}
export default ScaleImg
